package com.lyandwc.lw_bbs.controller;

import com.alibaba.fastjson.JSONObject;
import com.lyandwc.lw_bbs.entity.Notification;
import com.lyandwc.lw_bbs.security.entity.UserAuthDetails;
import com.lyandwc.lw_bbs.service.NotificationService;
import com.lyandwc.lw_bbs.service.UserService;
import com.lyandwc.lw_bbs.utils.ResponseUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/notifications")
public class NotificationController {
    private UserService userService;
    private NotificationService notificationService;

    public NotificationController(UserService userService, NotificationService notificationService) {
        this.userService = userService;
        this.notificationService = notificationService;
    }

    @PreAuthorize(value = "hasAnyRole('ADMIN', 'USER')")
    @RequestMapping(method = RequestMethod.GET)
    public JSONObject getNotifications(
            Authentication authentication
    ) {
        int userId = (int) authentication.getCredentials();
        List<Notification> notifications = notificationService.listNotificationsByUid(userId);
        return ResponseUtils.success(notifications);
    }

    @PreAuthorize(value = "hasAnyRole('ADMIN', 'USER')")
    @RequestMapping(value = "/unread", method = RequestMethod.GET)
    public JSONObject getUnreadNotifications(
            Authentication authentication
    ) {
        int userId = (int) authentication.getCredentials();
        List<Notification> unreadNotifications = notificationService.listUnreadNotificationsByUid(userId);
        return ResponseUtils.success(unreadNotifications);
    }

    @PreAuthorize(value = "hasAnyRole('ADMIN', 'USER')")
    @RequestMapping(value = "/unread/{id}", method = RequestMethod.PUT)
    public JSONObject updateNotification(
            Authentication authentication,
            @PathVariable int id
    ) {
        int userId = (int) authentication.getCredentials();
        Notification notification = notificationService.getById(id);
        if (notification != null) {
            if (notificationService.checkIsOwner(id, userId)) {
                notification.setReceived(1);
                notificationService.updateById(notification);
                return ResponseUtils.success(null);
            } else {
                return ResponseUtils.fail("Illegal access.");
            }
        }
        return ResponseUtils.fail("No such notification.");
    }
}
